<?php

/**
 * @version February 6, 2011
 * @Author Brice
 * This is the view file.
 * It controls the major file to manipulate data
 *
 */
echo "<html><body>";

include '../db-control/inc/functions.php';
require '../model/Major.php';
include '../db-control/dbMajor.php';

//update a major if the user is trying to do so
if (isset ($_POST['update']) && $_POST['update'] != '') {
    $name = $_POST['update'];
    $m = new Major(); //creates a new instance of Major()
    $m->setName($name); //sets the major name
    $db = new dbMajor();
    $exists = $db->checkName($m); //checks to see if the name is a real major
    if (!$exists) {
        echo "<b>Major with name '$name' does not exist...</b>";
    } else {
        $m->setName($_POST[name]); //sets the major name
        $result = $db->updateName($m); //updates the major with the data we've set
        if (!$result) {
            echo "<b>Could not update major with name '$name'...</b>";
        }
    }
} else {
    if (isset($_POST['add'])) {
        $m = new Major();
        $m->setName($_POST['name']);
        $db = new dbMajor();
        $result = $db->addMajor($m);
        if (!$result) {
            echo "<b>Please enter some major information</b>";
        }
    }

    if (isset($_POST['deleteButton'])) {
        $m = new Major(); //creates a new Major object (i.e. creates a new major)
        $m->setName($_POST['deleteName']);
        $db = new dbMajor();
        $result = $db->deleteMajor($m);
        if (!$result) {
            echo "<b>Could not delete major with name '$_POST[deleteName]'...</b>";
        }
    }
}


//displays the web form used for adding a new major
echo <<<_FORM


<form action='viewMajor.php' method='post'>
<table>
    <tr><td colspan='2'>Specify an name to change a major's data</td><td><input type='text' size='4' name='update' /></td></tr>
    <tr><td>Name:</td><td><input type='text' value='' name='name' /></td></tr>
    <tr><td></td><td align='right'><input type='submit' value='Add Major' name='add'/></td></tr>
</table>
</form>


_FORM;

displayMajors(); //displays the major list


echo "</body></html>";

function displayMajors() {
    $db = new dbMajor(); //gets all the majors from the database
    $result = $db->getAllMajors();
    echo "<table width='200px'>";
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        echo "<tr><td>$row[name]</td><td></td></tr>";
        echo "<tr><td align='right'>Name:</td><td align='left'>$row[name]</td></tr>";
        echo "<tr><td colspan='2' align='right'><form action='viewMajor.php' method='post'><input type='hidden' value='$row[name]' name='deleteName' /><input type='submit' value='Delete' name='deleteButton' /></form></td><td></td></tr>";
        echo "<tr><td colspan='2'><hr /></td><td></td></tr>";
    }
    echo "</table>";
}
?>

